package com.xls.resource.dialog;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;

import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.lzz.bottomencapsulation.BuildConfig;
import com.lzz.bottomencapsulation.entity.VersionEntity;
import com.lzz.bottomencapsulation.net.RequestCallBack;
import com.lzz.bottomencapsulation.net.RetrofitBase;
import com.lzz.bottomencapsulation.utils.AppUtils;
import com.lzz.bottomencapsulation.utils.LUtils;
import com.lzz.bottomencapsulation.utils.TUtils;
import com.xls.resource.R;
import com.xls.resource.dialog.utils.download.DownloadListener;
import com.xls.resource.dialog.utils.download.DownloadUtils;
import com.xls.resource.dialog.utils.download.FileEntity;
import com.xls.resource.dialog.utils.download.PackageUtil;
import com.xls.resource.dialog.utils.download.RequestManager4;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.observers.DisposableObserver;


/***
 @package ${package}
 @filename ${app版本更新}
 */
public class VersionDialog extends HintPW2 implements View.OnClickListener {
    VersionEntity versionEntity;
    Activity activity;
    String code;
    public VersionDialog(Activity context, VersionEntity versionEntity,String code) {
        super(context);
        this.versionEntity=versionEntity;
        this.activity=context;
        this.code=code;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        title="版本更新";
        hint=versionEntity.getContent();
        super.onCreate(savedInstanceState);
        setCanceledOnTouchOutside(!versionEntity.isForceUpdate());
        setCancelable(!versionEntity.isForceUpdate());
        setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (v.getId()== R.id.h2_tv_confirm){
            if (h2_tv_confirm.getText().toString().equals("安装")){
                AppUtils.anZhuangAPk(context,versionEntity.getFilePath());
            }else if (h2_tv_confirm.getText().toString().equals("确定")){
                h2_tv_confirm.setText("下载中");
                getPermissions(code);
            }
        }else if (v.getId()==R.id.h2_tv_cancel){
            if (versionEntity.isForceUpdate()){
                TUtils.showShort(context,"此版本为强制更新，不更新将无法使用");
            }else {
                dismiss();
            }
        }
    }


    private void getPermissions(String code) {
        XXPermissions.with(activity)
                // 申请单个权限
                .permission(Permission.REQUEST_INSTALL_PACKAGES)
                .permission(Permission.READ_MEDIA_IMAGES)
                .permission(Permission.READ_MEDIA_VIDEO)
                .permission(Permission.READ_MEDIA_AUDIO)
                .request(new OnPermissionCallback() {

                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        if (all) {
                            getDownLoadUrl(code);
                        }else {
                            h2_tv_confirm.setText("确定");
                        }
                    }

                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        h2_tv_confirm.setText("确定");
                        if (never) {
                            XXPermissions.startPermissionActivity(activity, permissions);
                        } else {
                            TUtils.showShort(activity,"请授予权限否则无法更新版本");
                        }
                    }
                });
    }

    private void getDownLoadUrl(String code) {

        RetrofitBase.getInstace(activity).setSubscribe(activity, RequestManager4.getInstance(activity).
                getUserCode2(BuildConfig.APKNAME,code,BuildConfig.KEYSTORE), new RequestCallBack<FileEntity>() {
            @Override
            public void onStart() {

            }

            @Override
            public void onStop() {
            }

            @Override
            public void onRequestSuccess(FileEntity requestData) {
                versionEntity.setUrl(requestData.getUrl());
                versionEntity.setMd5(requestData.getFileMd5());
                versionEntity.setFileSize(requestData.getFileSize());
                downLoadApk(getBaseUrl(versionEntity.getUrl()), versionEntity.getFilePath(), versionEntity);
            }

            @Override
            public void onRequestfail(String errno, String errmsg) {
                TUtils.showShort(context,errmsg);
                h2_tv_confirm.setText("确定");
            }
        });
//         downLoadApk(getBaseUrl(versionEntity.getUrl()), versionEntity.getFilePath(), versionEntity);
    }

    DownloadUtils downloadUtils;

    public DownloadUtils getDownloadUtils() {
        return downloadUtils;
    }

    /**
     * 下载文件
     * @param baseurl
     * @param filePath
     * @param requestData
     */
    private void downLoadApk(String baseurl,String filePath, VersionEntity requestData) {
        downloadUtils= new DownloadUtils(baseurl,0, new DownloadListener() {
            @Override
            public void onStartDownload(long id) {
                h2_tv_confirm.setText("下载中");
            }

            @Override
            public void onProgress(long id, int progress) {
                hEtCarnum.setText("下载中 "+progress+"%");
            }

            @Override
            public void onFinishDownload(long id) {
                LUtils.e("onFinishDownload");
            }

            @Override
            public void onFail(long id, String errorInfo) {
                LUtils.e("onFail"+errorInfo);
            }

            @Override
            public void onError(long id, String errorInfo) {

            }

            @Override
            public void onComplete(Long id) {

            }
        });
        downloadUtils.download(0,requestData.getUrl(), filePath, new DisposableObserver() {
            @Override
            public void onNext(Object o) {

            }

            @Override
            public void onError(@NonNull Throwable e) {
                h2_tv_confirm.setText("确定");
            }

            @Override
            public void onComplete() {
                File file=new File(filePath);
                if (file.exists()&&file.length()==versionEntity.getFileSize()&& PackageUtil.computeMD5(new File(filePath)).toUpperCase().equals(versionEntity.getMd5().toUpperCase())){
                    hEtCarnum.setText("下载成功");
                    h2_tv_confirm.setText("安装");
                    AppUtils.anZhuangAPk(context,versionEntity.getFilePath());
                }
            }
        });
    }

    private String getBaseUrl(String u) {
        try {
            URL url=new URL(u);
            return url.getProtocol()+"://"+url.getAuthority()+"/";
        } catch (MalformedURLException e) {
        }
        return "";
    }

    @Override
    public void dismiss() {
        if (downloadUtils!=null&&downloadUtils.getObservable()!=null){downloadUtils.getObservable().dispose();}
        super.dismiss();
    }
}
